package com.huxiaohui.ssbx.utils;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;

@Slf4j
public class SessionMessage {
    /**
     * 发送文本消息
     */
    public static void sendMessage(WebSocketSession session, String message, String type) {
        if (session != null && session.isOpen()) {
            try {
                Map<String, Object> map = Map.of(
                        "type", type,
                        "message", message,
                        "timestamp", System.currentTimeMillis()
                );
                String jsonMessage = JSONUtil.toJsonStr(map);
                session.sendMessage(new TextMessage(jsonMessage));
            } catch (IOException e) {
                log.error("发送消息失败", e);
            }
        }
    }

    /**
     * 发送音频消息
     */
    public static void sendAudioMessage(WebSocketSession session, byte[] audioData) {
        if (audioData.length == 0) return;
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new BinaryMessage(audioData));
            } catch (IOException e) {
                log.error("发送音频消息失败", e);
            }
        }
    }
}
